//
//  ZqlOAuthVC.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/18.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class ZqlOAuthVC: UIViewController {
    
    let webView=UIWebView()
    
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    //关闭视图控制器
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //点击测试账号按钮的方法
    @objc private func testAccount(){
        //本地代码 和webView交互
        let jsString="document.getElementById('userId').value='15147046787@163.com',document.getElementById('passwd').value='ql719903'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //关闭按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //测试账号按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "testAccount")

        loadOAuth()
    }
    
    //在页面将要消失的时候dismiss
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    
    //使用webView加载授权页面
    private func loadOAuth(){
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri="+redirect_uri
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
}


   //加扩展  处理webView的代理方法
   extension ZqlOAuthVC: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    
    //获取成功后的授权码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //如果urlString为空 返回失败
        guard let urlString = request.URL?.absoluteString else{
            return false
        }
        
        //判断URLString中是否包含code码
        if urlString.containsString("code"){
            guard let qurey = request.URL?.query else{
                return false
            }
            
           let codeString="code="
            //截取字符串
           let code = (qurey as NSString).substringFromIndex(codeString.characters.count)
            //用code码换取token令牌
            ZqlAccountVM.shardAccountVM.loadAccessToken(code, finished: { (isSuccess) -> () in
                if isSuccess {
                    //登录成功后 将访客界面dismiss掉
                    self.dismissViewControllerAnimated(true, completion: nil)
                    //将根视图设为欢迎界面(发送通知)
                    NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)

                }else{
                    
                    SVProgressHUD.showErrorWithStatus("登录失败,请检查网络")
                }
                
            })
            
            return false
        }
        
        return true
    }
    
        
    
    
}

